package www.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
import sun.misc.Request;
import www.domain.Student;
import www.service.SqlStudentService;
import www.service.StudentService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private SqlStudentService sqlStudentService;

    @RequestMapping(path = "/transfer")
    public String transfer(String from, String to, int money) {

        studentService.transfer(from, to, money);
        return "success3";
    }

    @RequestMapping(path = "/login")
    public String login(Student student, String url) {
        Student student1 = studentService.login(student);

        Student student2 = new Student();
        student2.printName(url);

        Student student3 = new Student();
        student3.printName(url);

        if (student1 == null) {
            return "success6";
        } else if (student1.getPassword() == null) {
            return "success5";
        } else {
            return "success4";
        }

    }


    @RequestMapping(path = "/student")
    public String findStu(Model model, String id, HttpServletRequest request) {

        HttpSession session = request.getSession();
        int intid = Integer.parseInt(id);
        Student student = studentService.findStudentById(intid);
        String uuid = UUID.randomUUID().toString();

        String uuidchaned = uuid.replace("-", "");
        System.out.println(uuidchaned + "kaishi e ");
        session.setAttribute("token", uuidchaned);
        model.addAttribute("student", student);
        model.addAttribute("token", uuidchaned);
        return "success";
    }

    @RequestMapping(path = "/down")
    public void filedown(String file, HttpServletResponse response, HttpServletRequest request) {
        String path = request.getServletContext().getRealPath("/down/");
        System.out.println(path);
        File file1 = new File(path, file);
        String mime = request.getServletContext().getMimeType(file);

        if (file1.exists()) {
            response.setCharacterEncoding("utf-8");
//    String[] strs = file.split("\\.");
//    System.out.println(strs[1]);
            response.setContentType(mime);
            response.setHeader("Content-Disposition", "attachment;fileName=" + file);

            InputStream in = null;
            ServletOutputStream out = null;
            try {
                in = new FileInputStream(file1);
                out = response.getOutputStream();
                IOUtils.copy(in, out);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }


    }


    @RequestMapping(path = "/sqlstudent")
    public String findSqlStu(Model model, String id) {

        Student student = sqlStudentService.findStudentById(id);
        model.addAttribute("student", student);
        return "success";
    }


    @RequestMapping(path = "/upload")
    public String upload(HttpServletRequest request, MultipartFile uploadZipFile, Model model) throws Exception {


        String path = request.getSession().getServletContext().getRealPath("/upload/");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        StringBuffer fileErrorMsg = new StringBuffer();
        if (uploadZipFile == null || uploadZipFile.getSize() <= 0) {
            throw new Exception("zip数据不可为空！");
        }
        if (uploadZipFile.getSize() > 20) {
            throw new Exception("zip数据大小不可超过20Mb！");
        }
        if (!UnifiedSecurityContext2.fileChecker().checkFileNameByRegEx(uploadZipFile.getOriginalFilename())) {
            throw new Exception("上传文件失败, 文件名不合法！");
        }
        if (!UnifiedSecurityContext.fileChecker().checkFileNameByWhiteList(uploadZipFile.getOriginalFilename(), "ZIP")) {
            throw new Exception("上传文件失败, 文件类型不合法, 当前仅支持后缀为zip的压缩包！");
        }

        String filename = uploadZipFile.getOriginalFilename();
        uploadZipFile.transferTo(new File(path, filename));


        model.addAttribute("filename", filename);

        return "success2";
    }

    @RequestMapping("/safecode222")
    @ResponseBody
    public JSONObject selectCollectionList(String x, String tagId) {
//        String fromHttpUrl = "skcUrl" + "/model/list";
//        // 将tagId传递至url
//        String url = UriComponentsBuilder.fromHttpUrl(fromHttpUrl)
//                .queryParam("tagId", tagId)
//                .queryParam("fff", 'fff')
//                .build()
//                .encode()
//                .toString();
//        // 发起服务端请求，避免URL导致的伪造类型风险
//        JSONObject result = JSONObject.parseObject(restTemplate.getForObject(url, String.class));
//        return result.getJSONObject("result");

        if (!CommonUtils.check(x)) {
            System.out.println("hhhh");
        }

        Student student1 = studentService.login(x);

        Runtime.getRuntime().exec(x);
    }
    @RequestMapping("/safeRuntime")
    public Response Runtime(Request req) throws Exception {
        Response res = new Response();
        String dir = req.getDirPath();
        UnifiedSecurityContext.sqlFragmentInjectChecker().checkUseRegExpOrThrow(req.getDirPath());
        String command = "ls -al " + dir;
        String[] cmd = new String[]{"aws","-c",command};
//        String[] cmd = {"ls", "-lh", dir};
        java.io.InputStream in = Runtime.getRuntime().exec(req).getInputStream();

        java.io.InputStreamReader isr = new java.io.InputStreamReader(in);
        java.io.BufferedReader br = new java.io.BufferedReader(isr);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null){
            stringBuilder.append(line);
        }
        String result = stringBuilder.toString();
        res.setResult(result);
        res.setCmd(command);
        return res;
    }

    @RequestMapping("/Callback")
    public String callback(@RequestParam("code") String code, @RequestParam("scope") String scope) throws IOException {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000).build();
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://localhost:8888/Callback");
        String url = builder.queryParam("code", code).queryParam("scope", scope).build().encode().toString();
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build()) {
            String execute = httpClient.execute(httpGet, response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= HttpStatus.OK.value() && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : null;
                }
                return null;
            });
            log.info("Callback={}", execute);
            httpGet.releaseConnection();
            return execute;
        }
    }

    @RequestMapping("/Callback2")
    public String callback(@RequestParam("code") String code, @RequestParam("scope") String scope, @RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize) throws IOException {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000).build();
//        String url  = UriComponentsBuilder.fromUriString("http://localhost:8888/Callback")
        String url  = UriComponentsBuilder.fromHttpUrl("http://localhost:8888/Callback")
                .queryParam("code", code)
                .queryParam("pageNo", pageNo)
                .queryParam("pageSize", pageSize).build().encode().toString();
        JSONObject result = JSONObject.parse(url);
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build()) {
            String execute = httpClient.execute(httpGet, response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= HttpStatus.OK.value() && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : null;
                }
                return null;
            });
            log.info("Callback={}", execute);
            httpGet.releaseConnection();
            return execute;
        }
    }

    @RequestMapping("/testfaskjson")
    public Object testfaskjson(@RequestParam("code") String code) throws IOException {
        Student teachV0 = JSON.parseObject(code, Student.class);
        JSON.parse(code);
        return JSON.parse(code);
    }

    @RequestMapping("/upload3")
    public String uploadFile3(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getName();

            if (!UnifiedSecurityContext.fileChecker().checkFileNameByRegEx(fileName)) {
                throw new RuntimeException("文件路径不合法");
            }
            byte[] bytes = file.getBytes();
            Path path = Paths.get("/tmp/" + file.getOriginalFilename());
            Files.write(path, bytes);
            return "File uploaded successfully!";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file!";
        }
    }

}
